package com.vpen.blog.config.security;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/* *
 * -@Version 1.0
 * -@Author:Vpen
 * -@Date:2021/7/8 10:39
 * -@Content: 生成Token和验证token工具类
 */
@Component
public class JwtTokenUtils {
    private static final String Claim_Key_UserName="sub";
    private static final String Claim_Key_Create="create";
    @Value("${jwt.secret}")
    private String secret; // 算是个密钥吧
    @Value("${jwt.expiration}")
    private  Long expiration;// token有效时间

    /* *
    * -@author Vpen
    * -@name generateToken
    * -@date 2021/7/8 10:48
    * -@param [userDetails]
    * -@return java.lang.String
    * -@作用:根据用户信息生成token
    */
    public String generateToken(UserDetails userDetails){
        Map<String,Object> claims = new HashMap<>();
        claims.put(Claim_Key_UserName,userDetails.getUsername());
        claims.put(Claim_Key_Create,new Date());
        return generateToken(claims);
    }
    /* *
    * -@author Vpen
    * -@name generateToken
    * -@date 2021/7/8 10:53
    * -@param [claims]
    * -@return java.lang.String
    * -@作用:根据荷载生成 JWT Token
    */
    public String generateToken(Map<String,Object> claims){
        return Jwts
                .builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();

    }
    /* *
     * 作者:Vpen
     * 描述:从token获取用户名.
     * */
    public String getUserNameFromToken(String token){
        String username;
        try {
            Claims claims=getClaimsFromToken(token);
            username = claims.getSubject();
        }catch (Exception e){
            username = null;
        }
        return username;
    }

    /* *
    * -@author Vpen
    * -@name validateToken
    * -@date 2021/7/8 11:33
    * -@param []
    * -@return boolean
    * -@作用: 验证Token是否有效
    */
    public boolean validateToken(String token,UserDetails userDetails){
        String username = getUserNameFromToken(token);
        return username.equals((userDetails.getUsername())) && !isTokenExpired(token);
    }


    /* *
     * 作者:Vpen
     * 描述:是否能刷新
     * */
    public boolean canRefresh(String token){
        /* *
         * 作者:Vpen
         * 描述: 如果失效了就可以刷新，否则不能刷新；
         * */
        return !isTokenExpired(token);
    }

    /* *
     * 作者:Vpen
     * 描述:刷新token
     * */
    public String refreshToken(String token){
        Claims claims = getClaimsFromToken(token);
        claims.put(Claim_Key_UserName,new Date());
        return generateToken(claims);
    }


    /* *
    * -@author Vpen
    * -@name isTokenExpired
    * -@date 2021/7/8 11:37
    * -@param [token]
    * -@return boolean
    * -@作用:判断token是否失效
    */
    private boolean isTokenExpired(String token) {
        Date expireDate = getExpriedDateFromToken(token);
        return expireDate.before(new Date());
    }
    /* *
     * 作者:Vpen
     * 描述:获取过期时间
     * */
    private Date getExpriedDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /* *
     * 作者:Vpen
     * 描述:获取Claims
     * */
    private Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts
                    .parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            claims=null;
        }
        return claims;

    }
    /* *
    * -@author Vpen
    * -@作用: 生成Token失效时间
    */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis()+expiration*1000);
    }


}
